//
//  MovieManager.m
//  WP_Movie
//
//  Created by GZCP1897 on 17/1/20.
//  Copyright © 2017年 GZCP1897. All rights reserved.
//

#import "MovieManager.h"
#import "MovieView.h"
#import "UIImage+MovieImage.h"
#import <Masonry.h>

#define WPScreenScale ([UIScreen mainScreen].bounds.size.width / [UIScreen mainScreen].bounds.size.height)

static MovieManager *_instance = nil;

@interface MovieManager()

@property(nonatomic, weak)UIView *fullScrenBackgroundView;
@property(nonatomic, weak)MovieView *movieV;
@property(nonatomic, weak)UIButton *closeBtn;
@property(nonatomic, weak)UIWindow *mainWindow;

@property(nonatomic, assign)CGFloat movieSourceScale;//视频资源比例 宽/高
@end

@implementation MovieManager
#pragma mark - Public
- (void)showMovieWithUrl:(NSURL *)url play:(BOOL)play{
    //1.判断是网络地址还是本地地址（先默认本地）
    if (!url) {//容错处理
        NSLog(@"Error--视频地址为空  -[WPMovieManager showMovieWithUrl:]");
        return;
    }
    //根据本地链接 获取MovieImage
    UIImage *image = [UIImage movieImageWith:url time:0.0];
    self.movieSourceScale = image.size.width / image.size.height;
    if (self.movieSourceScale < 1) {
        NSString *name = @"视频宽高比例错误";
        NSString *reason = @"一般视频资源宽度大于高度，按照4：3或者16：9";
        NSString *movieWidth = [NSString stringWithFormat:@"%f", image.size.width];
        NSString *movieHeight = [NSString stringWithFormat:@"%f", image.size.height];
        NSDictionary *dict = @{@"movieSourceWidth" : movieWidth, @"movieSourceHeight" : movieHeight};
        NSException *ception = [[NSException alloc] initWithName:name reason:reason userInfo:dict];
        @throw ception;
    }
    
    UIWindow *mainW = [UIApplication sharedApplication].keyWindow;
    self.mainWindow = mainW;
    
    UIView *fullScreenBackV = [[UIView alloc] init];
    fullScreenBackV.backgroundColor = [UIColor clearColor];
    self.fullScrenBackgroundView = fullScreenBackV;
    [mainW addSubview:fullScreenBackV];
    
    __weak typeof(self)weakSelf = self;
    MovieView *movieV = [[MovieView alloc] initWithFileUrl:url fullScreen:^{
        [weakSelf movieFullScreen];
    } deFullScreen:^{
        [weakSelf movieDefullScreen];
    }];
    self.movieV = movieV;
    [mainW addSubview:movieV];

    
    //关闭按钮
    UIButton *closeBtn = [[UIButton alloc] init];
//    UIImage *closeimage = [UIImage imageNamed:@"close"];
    [closeBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [closeBtn setImage:[UIImage imageNamed:@"close_icon"] forState:UIControlStateHighlighted];
    [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.closeBtn = closeBtn;
    [mainW addSubview:closeBtn];
    
    //添加约束
    [fullScreenBackV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(mainW);
    }];
    
    [movieV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(mainW);
        make.width.equalTo(@300);
        make.height.equalTo(movieV.mas_width).multipliedBy(1 / self.movieSourceScale);
    }];
    
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(movieV);
        make.right.equalTo(movieV);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];

}

#pragma mark - Private
- (void)movieFullScreen{
    self.fullScrenBackgroundView.backgroundColor = [UIColor blackColor];
    [self.movieV mas_remakeConstraints:^(MASConstraintMaker *make) {
        if (WPScreenScale < 1) {
            //竖屏
            make.width.equalTo(self.mainWindow);
        }else{
            //横屏
            if (WPScreenScale > self.movieSourceScale) {
                //按照高度
                make.height.equalTo(self.mainWindow);
            }else{
                //按照宽度
                make.width.equalTo(self.mainWindow);
            }
        }
        make.width.equalTo(self.movieV.mas_height).multipliedBy(self.movieSourceScale).priorityLow();
        make.height.equalTo(self.movieV.mas_width).multipliedBy(1 / self.movieSourceScale).priorityLow();
        make.center.equalTo(self.mainWindow);
    }];
    //other coding...
}

- (void)movieDefullScreen{
    self.fullScrenBackgroundView.backgroundColor = [UIColor clearColor];
    [self.movieV mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@300);
        make.height.equalTo(self.movieV.mas_width).multipliedBy(1 / self.movieSourceScale);
        make.center.equalTo(self.mainWindow);
    }];
    //other coding...
    
}

//关闭按钮点击
- (void)closeBtnClick:(UIButton *)btn{
    [self.closeBtn removeFromSuperview];
    [self.movieV removeFromSuperview];
    [self.fullScrenBackgroundView removeFromSuperview];
}

#pragma mark - signal
+ (instancetype)shareManager{
    return [[self alloc] init];
}

- (instancetype)init{
    if (self = [super init]) {
        
    }
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

//copy在底层 会调用copyWithZone:
+ (id)copyWithZone:(struct _NSZone *)zone{
    return  _instance;
}

+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
    return _instance;
}

@end
